import React from 'react';
import PropTypes from 'prop-types';
import {Table, Card, Button, Row, Col, Form, Spin, Input, Popconfirm, message as msg} from 'antd';
import TextInput from 'Shared/components/TextInput';
import routes from './routes';
import {newOrUpdateValidator} from './validator';
import Return from '../common/Return';
import {injectIntl} from './intl';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {dutyUnitType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import {getDutyUnitsQuickly, getDetail} from './api';
import SearchSelect from 'Shared/components/SearchSelect';
import DutyUnitSelectPanel from './DutyUnitSelectPanel';
import PartSelectPanel from './PartSelectPanel';
import ProductCategorySelectPanel from './ProductCategorySelectPanel';
import SearchInput from 'Shared/components/SearchInput';

const FormItem = Form.Item;
export class NewPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        data: [],
        details: [],
        showDutyUnit: false,
        showPart: false,
        showReplacedPart: false,
        showProductCategory: false
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    labelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `${d.code}`;
        return '';
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data, details} = this.state;
        const isValid = newOrUpdateValidator(data, details);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        this.props.onSubmit(data, details)
            .then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSearchDutyUnit = value =>
        getDutyUnitsQuickly({
            filter: value,
            type: dutyUnitType.责任单位
        })
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    onSelectDutyUnit = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                dutyUnitId: data.id,
                dutyUnitCode: data.code,
                dutyUnitName: data.name
            }),
            showDutyUnit: false,
            hasOperat: true
        });
    }
    onClickDutyUnit = () => {
        this.setState({showDutyUnit: true});
    }
    onCloseDutyUnit = () => {
        this.setState({showDutyUnit: false});
    }
    onSelectPart = data => {
        if(this.state.data.replacedPartId === data.id)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.replacedPartId',
                defaultMessage: '选择的原备件不能和替换备件相同'
            }));
        this.setState({
            data: Object.assign({}, this.state.data, {
                partId: data.id,
                partCode: data.code,
                partName: data.name
            }),
            showPart: false,
            hasOperat: true
        });
    }
    onClickPart = () => {
        this.setState({showPart: true});
    }
    onClosePart = () => {
        this.setState({showPart: false});
    }
    onSelectReplacedPart = data => {
        if(this.state.data.partId === data.id)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.partId',
                defaultMessage: '选择的替换备件不能和原备件相同'
            }));
        this.setState({
            data: Object.assign({}, this.state.data, {
                replacedPartId: data.id,
                replacedPartCode: data.code,
                replacedPartName: data.name
            }),
            showReplacedPart: false,
            hasOperat: true
        });
    }
    onClickReplacedPart = () => {
        this.setState({showReplacedPart: true});
    }
    onCloseReplacedPart = () => {
        this.setState({showReplacedPart: false});
    }
    onClickProductCategory = () => {
        this.setState({
            showProductCategory: !this.state.showProductCategory
        });
    }
    onCloseProductCategory = () => {
        this.setState({showProductCategory: false});
    }
    onSelectProductCategory = value => {
        const details = this.state.details;
        value.map(p => {
            const detail = this.state.details.find(d => d.productCategeryId === p.id);
            if(!detail) {
                const detail = {
                    productCategeryId: p.id,
                    productCategeryCode: p.code
                };
                details.push(detail);
            }
            return p;
        });
        this.setState({
            showProductCategory: false,
            hasOperat: true,
            details
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.details.filter(p => p.productCategeryId !== id);
        this.setState({
            details,
            hasOperat: true
        });
    }
    render() {
        const {data, details, isValidate} = this.state;
        const {formatMessage} = this.props.intl;
        if(this.props.brands.length === 1 && !this.props.id) {
            data.brandId = this.props.brands[0].value;
            data.brandName = this.props.brands[0].text;
        }
        const dutyUnitInfo = data.dutyUnitId ? {
            id: data.dutyUnitId,
            code: data.dutyUnitCode,
            name: data.dutyUnitName,
        } : null;
        
        const columns = [{
            title: formatMessage({
                id: 'newPanel.column.productCategeryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategeryCode',
        }, {
            title: details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'addPanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'addPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'productCategeryId',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'newPanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'newPanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.operation.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={isValidate && !data.brandId ? 'error' : null}
                                        required={!data.id}>
                                        {this.props.id ? `(${data.brandCode})${data.brandName}` : <WrappedSelect
                                            name="brandId"
                                            options={this.props.brands}
                                            value={data.brandId}
                                            onChange={this.onChange} />}
                                    </FormItem>
                                </Col>
                                {data.id ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dutyUnitId',
                                            defaultMessage: '供应商'
                                        })}
                                        {...FORM_OPTIONS.item} >
                                        {data.dutyUnitCode}
                                    </FormItem>
                                </Col> : <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dutyUnitId',
                                            defaultMessage: '供应商'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={!data.dutyUnitId && isValidate ? 'error' : null}
                                        required>
                                        {
                                            data.brandId ? <SearchSelect
                                                value={dutyUnitInfo}
                                                placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.form.dutyUnitId.placeholder',
                                                    defaultMessage: '请输入供应商名称或编号进行查询'
                                                })}
                                                onSelect={this.onSelectDutyUnit}
                                                onSearch={this.onSearchDutyUnit}
                                                keyIndex="id"
                                                labelMap={this.labelMap}
                                                onClickSearchBtn={this.onClickDutyUnit} /> : <TextInput name="dutyUnitId"
                                                value={''} disabled placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.dealerComp.placeholder',
                                                    defaultMessage: '请先选择品牌'
                                                })} />
                                        }
                                    </FormItem>
                                </Col>
                                }
                                {data.id ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partId',
                                        defaultMessage: '原备件编号'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.partCode}
                                    </FormItem>
                                </Col> : <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partId',
                                        defaultMessage: '原备件编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={isValidate && !data.partId ? 'error' : null}
                                    required={!data.id}>
                                        {
                                            data.brandId ? <SearchInput
                                                disabled={true}
                                                value={data.partCode}
                                                id={data.partId}
                                                onClickSearchBtn={this.onClickPart} /> : <TextInput name="supplierId"
                                                value={''} disabled placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.dealerComp.placeholder',
                                                    defaultMessage: '请先选择品牌'
                                                })} />
                                        }
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partName',
                                        defaultMessage: '原备件名称'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.partName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.replacedPartCode',
                                        defaultMessage: '替换备件编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={isValidate && !data.replacedPartId ? 'error' : null}
                                    required={!data.id}>
                                        {
                                            data.brandId ? <SearchInput
                                                disabled={true}
                                                value={data.replacedPartCode}
                                                id={data.replacedPartId}
                                                onClickSearchBtn={this.onClickReplacedPart} /> : <TextInput name="supplierId"
                                                value={''} disabled placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.dealerComp.placeholder',
                                                    defaultMessage: '请先选择品牌'
                                                })} />
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.replacedPartName',
                                        defaultMessage: '替换备件名称'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.replacedPartName}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.data.remark',
                                        defaultMessage: '备注'
                                    })}{...FORM_ROW_OPTIONS.item}><TextInput
                                            name="remark"
                                            type="textarea"
                                            value={data.remark}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'newPanel.operation.detail',
                                defaultMessage: '不供车型清单'
                            })} extra={<div>
                                <Button
                                    size="small"
                                    onClick={this.onClickProductCategory}>
                                    {formatMessage({
                                        id: 'newPanel.btn.add',
                                        defaultMessage: '增加清单'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="productCategeryId"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'newPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                    {
                        this.state.showDutyUnit &&
                        <DutyUnitSelectPanel
                            type={dutyUnitType.索赔供应商}
                            selectKey={data.dutyUnitId}
                            onCancel={this.onCloseDutyUnit}
                            onSelect={this.onSelectDutyUnit} />
                    }
                    {
                        this.state.showPart &&
                        <PartSelectPanel
                            brandId={data.brandId}
                            selectKey={data.partId}
                            onCancel={this.onClosePart}
                            onSelect={this.onSelectPart} />
                    }
                    {
                        this.state.showReplacedPart &&
                        <PartSelectPanel
                            brandId={data.brandId}
                            selectKey={data.replacedPartId}
                            onCancel={this.onCloseReplacedPart}
                            onSelect={this.onSelectReplacedPart} />
                    }
                    {
                        this.state.showProductCategory &&
                        <ProductCategorySelectPanel
                            currentSelectRowkeys={details}
                            selectKey={data.productCategoryId}
                            onCancel={this.onCloseProductCategory}
                            onSelect={this.onSelectProductCategory} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    data: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    brands: PropTypes.array,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch, onSubmit} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id,
            currency: item.currency
        })) : [];
        return brands;
    }
);
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    brands: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmit(data, details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
